package com.nxk.modules.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class RuntimeExceptionHandle {


    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomException.class)
    public ResultEntity bizExceptionHandler(HttpServletRequest req, CustomException e) {
        log.error("发生业务异常！原因是：{}", e.getErrorMsg());
        return ResultEntity.fail(String.valueOf(e.getErrorCode()), e.getErrorMsg());
    }


    /**
     * 前端提交参数实体类校验失败会产生这个异常
     * @param exception
     * @return
     */
    @ExceptionHandler(value = {ConstraintViolationException.class})
    public ResultEntity handleException(ConstraintViolationException exception) {
        return ResultEntity.fail(exception.getMessage());
    }


    /**
     * 前端提交参数,入参校验失败会产生这个异常
     * @param exception
     * @return
     */
    @ExceptionHandler(value = {BindException.class})
    public ResultEntity handleException(BindException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        StringBuilder errorInfo = new StringBuilder();
        for (ObjectError allError : bindingResult.getAllErrors()) {
            if (errorInfo.toString().equals("")){
                errorInfo.append(allError.getDefaultMessage());
            } else {
                errorInfo.append(", "+allError.getDefaultMessage());
            }
        }
        return ResultEntity.fail(errorInfo.toString());
    }


    /**
     * 访问无权限时处理
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = {UnauthenticatedException.class, UnauthorizedException.class})
    public ResultEntity handleException(HttpServletRequest req, Exception e)  {
        return ResultEntity.fail(RequestStatus.ERROR_NOT_PERM.getCode(),RequestStatus.ERROR_NOT_PERM.getMessage());
    }

    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ResultEntity exceptionHandler(HttpServletRequest req, Exception e) {
        log.error(e.getMessage());
        return ResultEntity.fail(RequestStatus.ERROR_UNKNOWN.getCode(), e.getMessage());
    }

}
